﻿using Learun.Util;
using Learun.Util.Constant;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.WorkFlow
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：研发部
    /// 日 期：2018.12.06
    /// 描 述：工作流模板(新)
    /// </summary>
    public class NWFSchemeService
    {
        #region 仓储
        Repository<NWFSchemeInfoEntity> _NWFSchemeInfoRepository => new Repository<NWFSchemeInfoEntity>();
        Repository<NWFSchemeAuthEntity> _NWFSchemeAuthRepository => new Repository<NWFSchemeAuthEntity>();
        Repository<NWFSchemeCategoryEntity> _NWFSchemeCategoryRepository => new Repository<NWFSchemeCategoryEntity>();
        Repository<NWFSchemeEntity> _NWFSchemeRepository => new Repository<NWFSchemeEntity>();
        #endregion
        #region 获取数据
        /// <summary>
        /// 获取流程分页列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="queryJson">查询条件</param>
        /// <returns></returns>
        public IEnumerable<NWFSchemeInfoEntity> GetInfoPageList(Pagination pagination, string queryJson)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT t.*,t2.ClassifyName AS CategoryName ");
                strSql.Append(",t1.F_Type,t1.F_CreateDate,t1.F_CreateUserId,t1.F_CreateUserName ");
                strSql.Append(" FROM LR_NWF_SchemeInfo t    LEFT JOIN LR_NWF_Scheme t1 ON  t.F_SchemeId = t1.F_Id  LEFT JOIN lr_nwf_flowclassify t2 ON t.F_Category=t2.FlowClassifyID   WHERE 1 =1 ");
                //var dp = new DynamicParameters();
                var dp = new List<SugarParameter>();
                if (!string.IsNullOrEmpty(queryJson))
                {
                    var queryParam = queryJson.ToJObject();
                    string ProjectId = string.Empty;
                    if (!queryParam["ProjectId"].IsEmpty())
                    {
                        dp.Add(new SugarParameter("ProjectId", queryParam["ProjectId"].ToString(), DbType.String));
                        strSql.Append(" AND t.ProjectId = @ProjectId");

                    }
                    else
                    {
                        strSql.Append(" AND IFNULL(t.ProjectId,'') =''");
                    }

                    if (!queryParam["keyword"].IsEmpty())
                    {
                        strSql.Append(" AND ( t.F_Name like @keyword OR t.F_Code like @keyword ) ");
                        dp.Add(new SugarParameter("keyword", "%" + queryParam["keyword"].ToString() + "%", DbType.String));
                    }
                    if (!queryParam["category"].IsEmpty())
                    {
                        strSql.Append(" AND t.F_Category = @category ");
                        dp.Add(new SugarParameter("category", queryParam["category"].ToString(), DbType.String));
                    }
                    if (!queryParam["plantType"].IsEmpty())
                    {
                        strSql.Append(" AND t2.plantType = @plantType ");
                        dp.Add(new SugarParameter("plantType", queryParam["plantType"].ToString(), DbType.String));
                    }
                    if (!queryParam["enabledMark"].IsEmpty())
                    {
                        strSql.Append(" AND t.F_EnabledMark =1");
                    }
                }
                //return this.BaseRepository().FindList<NWFSchemeInfoEntity>(strSql.ToString(), dp, pagination);
                return SqlSugarHelper.Db.SqlQueryable<NWFSchemeInfoEntity>(strSql.ToString()).AddParameters(dp).ToPageList(pagination.page, pagination.rows);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取自定义流程列表
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        /// <returns></returns>
        public IEnumerable<NWFSchemeInfoEntity> GetInfoList(UserInfo userInfo, string ProjectId)
        {
            try
            {
                string userId = userInfo.userId;
                string postIds = userInfo.postIds;
                string roleIds = userInfo.roleIds;
                List<NWFSchemeAuthEntity> list = _NWFSchemeAuthRepository.GetList(t => t.F_ObjId == null
                    || userId.Contains(t.F_ObjId)
                    || postIds.Contains(t.F_ObjId)
                    || roleIds.Contains(t.F_ObjId)
                    );
                string schemeinfoIds = "";
                foreach (var item in list)
                {
                    schemeinfoIds += "'" + item.F_SchemeInfoId + "',";
                }
                schemeinfoIds = "(" + schemeinfoIds.Remove(schemeinfoIds.Length - 1, 1) + ")";
                string PlantType = string.Empty;
                if (!ProjectId.IsEmpty())
                {
                    PlantType = Util.Constant.ConstantBiz.PLANTTYPE_PROJECT;
                }
                else
                {
                    PlantType = Util.Constant.ConstantBiz.PLANTTYPE_UNIT;
                }
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT 
                                    t.* 
                                FROM lr_nwf_schemeinfo t
                                INNER  JOIN lr_nwf_flowclassify t1 ON t.F_Category=t1.FlowClassifyID
                                WHERE t.F_EnabledMark = 1  
                                AND t.F_Mark = 1 
                                AND t.F_Id in " + schemeinfoIds +
                                " AND t.ProjectId='" + ProjectId + "'" +
                                " AND t1.PlantType='" + PlantType + "'");

                //return this.BaseRepository().FindList<NWFSchemeInfoEntity>(strSql.ToString());
                return SqlSugarHelper.Db.SqlQueryable<NWFSchemeInfoEntity>(strSql.ToString()).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取流程模板列表 
        /// </summary>
        /// <param name="categoryId">分类Id</param>
        /// <returns></returns>
        public IEnumerable<NWFSchemeInfoEntity> GetInfoListByCategoryId(string categoryId)
        {
            var strSql = new StringBuilder();
            strSql.Append("SELECT * ");
            strSql.Append(" FROM lr_nwf_schemeinfo t WHERE t.F_EnabledMark = 1 ");

            strSql.Append("AND (t.ProjectId='' OR t.ProjectId IS NULL) ");
            //var dp = new DynamicParameters();
            var dp = new List<SugarParameter>();
            if (!string.IsNullOrEmpty(categoryId))
            {
                strSql.Append(" AND  t.F_Category =@categoryId ");
                dp.Add(new SugarParameter("categoryId", categoryId, DbType.String));
            }
            //return this.BaseRepository().FindList<NWFSchemeInfoEntity>(strSql.ToString(), dp);
            return SqlSugarHelper.Db.SqlQueryable<NWFSchemeInfoEntity>(strSql.ToString()).AddParameters(dp).ToList();
        }


        /// <summary>
        /// 获取流程列表
        /// </summary>
        /// <returns></returns>
        public IEnumerable<NWFSchemeInfoEntity> GetInfoList()
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT * ");
                strSql.Append(" FROM LR_NWF_SchemeInfo t WHERE t.F_EnabledMark = 1 ");
                //return this.BaseRepository().FindList<NWFSchemeInfoEntity>(strSql.ToString());
                return SqlSugarHelper.Db.SqlQueryable<NWFSchemeInfoEntity>(strSql.ToString()).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        ///  获取流程分类树形数据
        /// </summary>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        public List<NWFSchemeCategoryEntity> GetCategoryTree(string ProjectId, string PlantType)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT
                                     t1.* 
                                FROM  lr_nwf_flowclassify t1  
                                WHERE 1=1 ");
                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!ProjectId.IsEmpty())
                {
                    dp.Add(new SugarParameter("ProjectId", ProjectId, DbType.String));
                    strSql.Append(" AND t1.ProjectId = @ProjectId ");
                }
                else
                {
                    strSql.Append(" AND IFNULL(t1.ProjectId,'') = '' ");
                }
                if (!PlantType.IsEmpty())
                {
                    dp.Add(new SugarParameter("PlantType", PlantType, DbType.String));
                    strSql.Append(" AND t1.PlantType = @PlantType ");
                }
                strSql.Append(" ORDER BY if(isnull(OrderID),1,0),OrderID ");
                //return this.BaseRepository().FindList<NWFSchemeCategoryEntity>(strSql.ToString(), dp).ToList<NWFSchemeCategoryEntity>();
                return SqlSugarHelper.Db.SqlQueryable<NWFSchemeCategoryEntity>(strSql.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        /// <summary>
        ///  获取流程分类数据
        /// </summary>
        /// <returns></returns>
        public List<NWFSchemeCategoryEntity> GetCategoryList(string queryJson)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                string ProjectId = string.Empty;
                if (!queryParam["ProjectId"].IsEmpty())
                {
                    ProjectId = queryParam["ProjectId"].ToString();
                }
                StringBuilder sqlStr = new StringBuilder();
                sqlStr.Append("select * from lr_nwf_flowclassify t  where 1 = 1 ");
                //var dp = new DynamicParameters();
                var dp = new List<SugarParameter>();
                if (!queryParam["keyword"].IsEmpty())
                {
                    sqlStr.Append(" AND  t.ClassifyName like @keyword ");
                    dp.Add(new SugarParameter("keyword", "%" + queryParam["keyword"].ToString() + "%", DbType.String));
                }
                if (!queryParam["PlantType"].IsEmpty())
                {
                    sqlStr.Append(" AND  t.PlantType=@PlantType ");
                    dp.Add(new SugarParameter("PlantType", queryParam["PlantType"].ToString(), DbType.String));
                }
                sqlStr.Append("AND t.ProjectId = @ProjectId order by if (isnull(OrderID),1,0),OrderID");
                dp.Add(new SugarParameter("ProjectId", ProjectId, DbType.String));
                //return this.BaseRepository("BaseDb").FindList<NWFSchemeCategoryEntity>(sqlStr.ToString(), dp).ToList<NWFSchemeCategoryEntity>();
                return SqlSugarHelper.Db.SqlQueryable<NWFSchemeCategoryEntity>(sqlStr.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        /// <summary>
        /// 获取流程分类数据
        /// </summary>
        /// <param name="plantType"> 流程分类00001单位平台，00002项目平台</param>
        /// <param name="ProjectId"> 项目ID</param>
        /// <returns></returns>
        public List<NWFSchemeCategoryEntity> GetNWFSchemeCategoryEntityList(string plantType, string ProjectId)
        {
            try
            {
                StringBuilder sqlStr = new StringBuilder();
                sqlStr.Append("select * from lr_nwf_flowclassify t  where 1 = 1 ");

                //var dp = new DynamicParameters();
                var dp = new List<SugarParameter>();
                if (!string.IsNullOrEmpty(plantType))
                {
                    sqlStr.Append(" AND  t.PlantType =@plantType ");
                    dp.Add(new SugarParameter("plantType", plantType, DbType.String));
                }
                if (!string.IsNullOrEmpty(ProjectId))
                {
                    sqlStr.Append(" AND  t.ProjectId =@ProjectId ");
                    dp.Add(new SugarParameter("ProjectId", ProjectId, DbType.String));
                }
                else
                {
                    sqlStr.Append("AND (t.ProjectId='' OR t.ProjectId IS NULL) ");
                }
                //return this.BaseRepository("BaseDb").FindList<NWFSchemeCategoryEntity>(sqlStr.ToString(), dp).ToList<NWFSchemeCategoryEntity>();
                return SqlSugarHelper.Db.SqlQueryable<NWFSchemeCategoryEntity>(sqlStr.ToString()).AddParameters(dp).ToList();

            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取流程分类实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        public NWFSchemeCategoryEntity GetCategoryForm(string keyValue)
        {
            return _NWFSchemeCategoryRepository.GetSingle(t => t.FlowClassifyID == keyValue);
        }

        /// <summary>
        /// 获取流程模板分页列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="userInfo">登录者信息</param>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        public IEnumerable<NWFSchemeInfoEntity> GetAppInfoPageList(Pagination pagination, UserInfo userInfo, string queryJson)
        {
            try
            {
                string userId = userInfo.userId;
                string postIds = userInfo.postIds;
                string roleIds = userInfo.roleIds;
                List<NWFSchemeAuthEntity> list = _NWFSchemeAuthRepository.GetList(t => t.F_ObjId == null
                    || userId.Contains(t.F_ObjId)
                    || postIds.Contains(t.F_ObjId)
                    || roleIds.Contains(t.F_ObjId)
                    );
                string schemeinfoIds = "";
                foreach (var item in list)
                {
                    schemeinfoIds += "'" + item.F_SchemeInfoId + "',";
                }
                schemeinfoIds = "(" + schemeinfoIds.Remove(schemeinfoIds.Length - 1, 1) + ")";


                var strSql = new StringBuilder();
                strSql.Append("SELECT * ");
                strSql.Append(" FROM LR_NWF_SchemeInfo t WHERE t.F_EnabledMark = 1  AND t.F_Mark = 1 AND F_IsInApp = 1 AND t.F_Id in " + schemeinfoIds);

                var queryParam = queryJson.ToJObject();
                string keyword = "";
                if (!queryParam["keyword"].IsEmpty())
                {
                    strSql.Append(" AND ( t.F_Name like @keyword OR t.F_Code like @keyword ) ");
                    keyword = "%" + queryParam["keyword"].ToString() + "%";
                }
                //return this.BaseRepository().FindList<NWFSchemeInfoEntity>(strSql.ToString(), new { keyword }, pagination);
                return SqlSugarHelper.Db.SqlQueryable<NWFSchemeInfoEntity>(strSql.ToString()).AddParameters(new { keyword }).ToPageList(pagination.page, pagination.rows);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取模板基础信息的实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        public NWFSchemeInfoEntity GetInfoEntity(string keyValue)
        {
            try
            {
                return _NWFSchemeInfoRepository.GetById(keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取模板基础信息的实体
        /// </summary>
        /// <param name="code">流程编号</param>
        /// <returns></returns>
        public NWFSchemeInfoEntity GetInfoEntityByCode(string code)
        {
            try
            {
                return _NWFSchemeInfoRepository.GetFirst(t => t.F_Code == code);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取模板基础信息的实体
        /// </summary>
        /// <param name="code">流程编号</param>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        public NWFSchemeInfoEntity GetInfoEntityByCodeAndProjectId(string code, string ProjectId)
        {
            try
            {
                //var dp = new DynamicParameters();
                var dp = new List<SugarParameter>();
                string PlantType = ConstantBiz.PLANTTYPE_UNIT;
                if (!ProjectId.IsEmpty())
                {
                    PlantType = ConstantBiz.PLANTTYPE_PROJECT;
                }
                var strSql = new StringBuilder();
                strSql.Append("SELECT t.* ");
                strSql.Append(" FROM lr_nwf_schemeinfo t,lr_nwf_flowclassify t2 WHERE t.F_Category=t2.FlowClassifyID AND t.F_EnabledMark = 1 ");

                if (!string.IsNullOrEmpty(ProjectId))
                {
                    strSql.Append(" AND  t.ProjectId =@ProjectId ");
                    dp.Add(new SugarParameter("ProjectId", ProjectId, DbType.String));
                }
                else
                {
                    strSql.Append("AND (t.ProjectId='' OR t.ProjectId IS NULL) ");
                }

                strSql.Append(" AND  t.F_Code =@F_Code ");
                dp.Add(new SugarParameter("F_Code", code, DbType.String));

                strSql.Append(" AND  t2.PlantType =@PlantType ");
                dp.Add(new SugarParameter("PlantType", PlantType, DbType.String));

                return SqlSugarHelper.Db.Ado.SqlQuerySingle<NWFSchemeInfoEntity>(strSql.ToString(), dp);
                //return this.BaseRepository().FindEntity<NWFSchemeInfoEntity>(t => t.F_Code == code && t.ProjectId == ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取流程模板权限列表
        /// </summary>
        /// <param name="schemeInfoId">模板信息主键</param>
        /// <returns></returns>
        public IEnumerable<NWFSchemeAuthEntity> GetAuthList(string schemeInfoId)
        {
            try
            {
                return _NWFSchemeAuthRepository.GetList(t => t.F_SchemeInfoId == schemeInfoId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取模板列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="schemeInfoId">流程信息主键</param>
        /// <returns></returns>
        public IEnumerable<NWFSchemeEntity> GetSchemePageList(Pagination pagination, string schemeInfoId)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT t.F_Id,t.F_SchemeInfoId,t.F_Type,t.F_CreateDate,t.F_CreateUserId,t.F_CreateUserName");
                strSql.Append(" FROM LR_NWF_Scheme t ");
                strSql.Append(" WHERE t.F_SchemeInfoId = @schemeInfoId ");
                //return this.BaseRepository().FindList<NWFSchemeEntity>(strSql.ToString(), new { schemeInfoId }, pagination);
                return SqlSugarHelper.Db.SqlQueryable<NWFSchemeEntity>(strSql.ToString()).AddParameters(new { schemeInfoId }).ToPageList(pagination.page, pagination.rows);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取模板的实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        public NWFSchemeEntity GetSchemeEntity(string keyValue)
        {
            try
            {
                return _NWFSchemeRepository.GetById(keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取模板的实体
        /// </summary>
        /// <param name="schemeInfoId">流程信息主键</param>
        /// <returns></returns>
        public NWFSchemeEntity GetSchemeEntityBySchemeInfoId(string schemeInfoId)
        {
            return _NWFSchemeRepository.GetFirst(s => s.F_SchemeInfoId == schemeInfoId);
        }

        /// <summary>
        /// 获取模板的实体 add by zhuxing
        /// </summary>
        /// <param name="schemeInfoId">流程信息主键</param>
        /// <returns></returns>
        public IEnumerable<NWFSchemeEntity> GetNewSchemeEntityBySchemeInfoId(string schemeInfoId)
        {
            //return this.BaseRepository().FindList<NWFSchemeEntity>(s => s.F_SchemeInfoId == schemeInfoId);
            return _NWFSchemeRepository.GetList(s => s.F_SchemeInfoId == schemeInfoId);
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 虚拟删除模板信息
        /// </summary>
        /// <param name="keyValue">主键</param>
        public void DeleteEntity(string keyValue)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                _NWFSchemeInfoRepository.Delete(t => t.F_Id.Equals(keyValue));
                _NWFSchemeAuthRepository.Delete(t => t.F_SchemeInfoId.Equals(keyValue));
                _NWFSchemeRepository.Delete(t => t.F_SchemeInfoId.Equals(keyValue));
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 保存模板信息
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="infoEntity">模板基础信息</param>
        /// <param name="schemeEntity">模板信息</param>
        /// <param name="authList">模板权限信息</param>
        public void SaveEntity(string keyValue, NWFSchemeInfoEntity infoEntity, NWFSchemeEntity schemeEntity, List<NWFSchemeAuthEntity> authList)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrEmpty(keyValue))
                {
                    infoEntity.Create();
                }
                else
                {
                    infoEntity.Modify(keyValue);
                }

                #region 模板信息
                if (schemeEntity != null)
                {
                    schemeEntity.F_SchemeInfoId = infoEntity.F_Id;
                    schemeEntity.Create();
                    _NWFSchemeRepository.Insert(schemeEntity);
                    infoEntity.F_SchemeId = schemeEntity.F_Id;
                }
                #endregion

                #region 模板基础信息
                if (!string.IsNullOrEmpty(keyValue))
                {
                    _NWFSchemeInfoRepository.Update(infoEntity);
                }
                else
                {
                    _NWFSchemeInfoRepository.Insert(infoEntity);
                }
                #endregion

                #region 流程模板权限信息
                string schemeInfoId = infoEntity.F_Id;
                _NWFSchemeAuthRepository.Delete(t => t.F_SchemeInfoId == schemeInfoId);
                foreach (var item in authList)
                {
                    item.Create();
                    item.F_SchemeInfoId = schemeInfoId;
                    _NWFSchemeAuthRepository.Insert(item);
                }
                #endregion

                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存模板信息 add by zhuxing
        /// </summary>
        /// <param name="currentSchemeInfo">当前模板数据</param>
        /// <param name="commonScheme">最新通用模板数据</param>
        public void SaveEntity(NWFSchemeInfoEntity currentSchemeInfo, NWFSchemeEntity commonScheme)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                NWFSchemeEntity insertData = new NWFSchemeEntity();
                insertData.Create();
                insertData.F_Content = commonScheme.F_Content;
                insertData.F_SchemeInfoId = currentSchemeInfo.F_Id;
                insertData.F_Type = 1;
                _NWFSchemeRepository.Insert(insertData);

                currentSchemeInfo.F_SchemeId = insertData.F_Id;
                _NWFSchemeInfoRepository.Update(currentSchemeInfo);
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 删流程分类
        /// </summary>
        /// <param name="keyValue">主键</param>
        public void CategoryDeleteEntity(string keyValue)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                _NWFSchemeCategoryRepository.Delete(t => t.FlowClassifyID == keyValue);
                var entity = _NWFSchemeInfoRepository.GetFirst(t => t.F_Category == keyValue);
                if (!entity.IsEmpty())
                {
                    _NWFSchemeInfoRepository.Delete(t => t.F_Id.Equals(entity.F_Id));
                    _NWFSchemeAuthRepository.Delete(t => t.F_SchemeInfoId.Equals(entity.F_Id));
                    _NWFSchemeRepository.Delete(t => t.F_SchemeInfoId.Equals(entity.F_Id));
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存流程分类
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="entity">流程分类实体</param>
        public void CategorySaveEntity(string keyValue, NWFSchemeCategoryEntity entity)
        {
            //IRepository db = new RepositoryFactory().BaseRepository();
            try
            {
                if (string.IsNullOrEmpty(keyValue))
                {
                    entity.Create();
                    _NWFSchemeCategoryRepository.Insert(entity);
                }
                else
                {
                    entity.Modify(keyValue);
                    _NWFSchemeCategoryRepository.Update(entity);
                }


            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 更新流程模板
        /// </summary>
        /// <param name="schemeInfoId">模板信息主键</param>
        /// <param name="schemeId">模板主键</param>
        public void UpdateScheme(string schemeInfoId, string schemeId)
        {
            try
            {
                NWFSchemeEntity nWFSchemeEntity = GetSchemeEntity(schemeId);

                NWFSchemeInfoEntity entity = new NWFSchemeInfoEntity
                {
                    F_Id = schemeInfoId,
                    F_SchemeId = schemeId
                };
                if (nWFSchemeEntity.F_Type != 1)
                {
                    entity.F_EnabledMark = 0;
                }
                _NWFSchemeInfoRepository.Update(entity);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 更新自定义表单模板状态
        /// </summary>
        /// <param name="schemeInfoId">模板信息主键</param>
        /// <param name="state">状态1启用0禁用</param>
        public void UpdateState(string schemeInfoId, int state)
        {
            try
            {
                NWFSchemeInfoEntity entity = new NWFSchemeInfoEntity
                {
                    F_Id = schemeInfoId,
                    F_EnabledMark = state
                };
                _NWFSchemeInfoRepository.Update(entity);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion
    }
}
